package br.com.cjweb.util.model;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import br.com.cjweb.util.exception.GerarSequenceException;

public abstract class AbstractModel
{
	private Connection conexao;

	protected Connection getConexao()
	{
		return conexao;
	}

	private void setConexao(Connection conexao)
	{
		this.conexao = conexao;
	}

	protected AbstractModel(Connection conexao)
	{
		setConexao(conexao);
	}

	protected void close(PreparedStatement ps)
	{
		if (ps != null)
		{
			try
			{
				ps.close();
			}
			catch (SQLException e)
			{
				e.printStackTrace();
			}
			finally
			{
				ps = null;
			}
		}
	}

	protected void close(PreparedStatement ps, ResultSet rs)
	{
		if (rs != null)
		{
			try
			{
				ps.close();
				rs.close();
			}
			catch (SQLException e)
			{
				e.printStackTrace();
			}
			finally
			{
				ps = null;
				rs = null;
			}
		}
	}

	public long getSequenceObjeto(String nomeSeguence) throws GerarSequenceException
	{
		PreparedStatement ps = null;
		ResultSet rs = null;
		
		
		long sequenciaIdObjeto = 0;
		try
		{
			ps = getConexao().prepareStatement("select nextval('" + nomeSeguence + "') as \"id\"");
			rs = ps.executeQuery();
			if (rs.next())
				sequenciaIdObjeto = rs.getLong("id");
			
			return sequenciaIdObjeto;
		}
		catch (SQLException e)
		{
			throw new GerarSequenceException(e);
		}
		
		finally
		{
			close(ps, rs);
		}
	}
}
